package experiment3.shudu001.views;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import experiment3.shudu001.models.GameEngine;

/**
 * 数独游戏棋盘视图
 * 负责数独棋盘的绘制和触摸交互处理
 * 主要功能：
 * 1. 绘制9x9数独网格
 * 2. 渲染单元格数字和笔记
 * 3. 高亮选中单元格和冲突单元格
 * 4. 处理用户触摸选择单元格事件
 */
public class SudokuBoard extends View {

    // 游戏逻辑引擎引用
    private GameEngine gameEngine;
    // 视图状态
    private int selectedRow = -1;  // 当前选中行（-1表示未选中）
    private int selectedCol = -1;  // 当前选中列
    // 绘制工具
    private final Paint thickLinePaint = new Paint();       // 粗线画笔（宫格线）
    private final Paint thinLinePaint = new Paint();        // 细线画笔（单元格线）
    private final Paint selectedCellPaint = new Paint();    // 选中单元格背景
    private final Paint conflictingCellPaint = new Paint(); // 冲突单元格背景
    private final Paint textPaint = new Paint();            // 普通数字样式
    private final Paint fixedTextPaint = new Paint();       // 固定数字样式
    private final Paint noteTextPaint = new Paint();        // 笔记数字样式

    public SudokuBoard(Context context, AttributeSet attrs) {
        super(context, attrs);
        initPaints();
    }

    /**
     * 初始化所有画笔配置
     */
    private void initPaints() {
        // 粗线配置（宫格边界）
        thickLinePaint.setStyle(Paint.Style.STROKE);
        thickLinePaint.setColor(Color.BLACK);
        thickLinePaint.setStrokeWidth(4);

        // 细线配置（单元格边界）
        thinLinePaint.setStyle(Paint.Style.STROKE);
        thinLinePaint.setColor(Color.BLACK);
        thinLinePaint.setStrokeWidth(1);

        // 选中单元格背景（浅蓝色）
        selectedCellPaint.setStyle(Paint.Style.FILL);
        selectedCellPaint.setColor(Color.parseColor("#6ab7ff"));

        // 冲突单元格背景（浅红色）
        conflictingCellPaint.setStyle(Paint.Style.FILL);
        conflictingCellPaint.setColor(Color.parseColor("#ef9a9a"));

        // 主数字样式配置
        textPaint.setColor(Color.BLACK);
        textPaint.setTextAlign(Paint.Align.CENTER);
        textPaint.setTextSize(60f);

        // 固定数字样式（加粗，稍大）
        fixedTextPaint.setColor(Color.BLACK);
        fixedTextPaint.setFakeBoldText(true);
        fixedTextPaint.setTextAlign(Paint.Align.CENTER);
        fixedTextPaint.setTextSize(64f);

        // 笔记数字样式（灰色，小号）
        noteTextPaint.setColor(Color.GRAY);
        noteTextPaint.setTextAlign(Paint.Align.CENTER);
        noteTextPaint.setTextSize(textPaint.getTextSize() / 2.5f);
    }

    /**
     * 绑定游戏引擎
     */
    public void setGameEngine(GameEngine gameEngine) {
        this.gameEngine = gameEngine;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (gameEngine == null) return;

        drawGrid(canvas);    // 绘制网格线
        drawCells(canvas);   // 绘制单元格内容
    }

    /**
     * 绘制数独网格线
     */
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            int size = Math.min(getMeasuredWidth(), getMeasuredHeight());
            setMeasuredDimension(size, size);
        }

        private void drawGrid(Canvas canvas) {
            int width = getWidth();
            int height = getHeight();
            int cellSize = Math.min(width, height) / 9;

        // 绘制所有细线（81个单元格）
        for (int i = 0; i <= 9; i++) {
            // 垂直线
            canvas.drawLine(i * cellSize, 0, i * cellSize, width, thinLinePaint);
            // 水平线
            canvas.drawLine(0, i * cellSize, width, i * cellSize, thinLinePaint);
        }

        // 绘制宫格粗线（3x3大格子）
        for (int i = 0; i <= 3; i++) {
            int pos = i * 3 * cellSize;
            // 垂直宫格线
            canvas.drawLine(pos, 0, pos, width, thickLinePaint);
            // 水平宫格线
            canvas.drawLine(0, pos, width, pos, thickLinePaint);
        }
    }

    /**
     * 绘制所有单元格内容
     */
    private void drawCells(Canvas canvas) {
        int cellSize = getWidth() / 9;

        for (int row = 0; row < 9; row++) {
            for (int col = 0; col < 9; col++) {
                // 绘制背景
                drawCellBackground(canvas, row, col);

                // 绘制数字或笔记
                int number = gameEngine.getCellValue(row, col);
                if (number != 0) {
                    drawNumberContent(canvas, row, col, number);
                } else {
                    drawNoteContent(canvas, row, col);
                }
            }
        }
    }

    /**
     * 绘制单元格背景（选中/冲突状态）
     */
    private void drawCellBackground(Canvas canvas, int row, int col) {
        if (row == selectedRow && col == selectedCol) {
            drawCellRect(canvas, row, col, selectedCellPaint);
        } else if (gameEngine.isConflictingCell(row, col)) {
            drawCellRect(canvas, row, col, conflictingCellPaint);
        }
    }

    /**
     * 在指定单元格绘制背景矩形
     */
    private void drawCellRect(Canvas canvas, int row, int col, Paint paint) {
        int cellSize = getWidth() / 9;
        int left = col * cellSize;
        int top = row * cellSize;
        canvas.drawRect(left, top, left + cellSize, top + cellSize, paint);
    }

    /**
     * 绘制主数字内容
     */
    private void drawNumberContent(Canvas canvas, int row, int col, int number) {
        Paint paint = gameEngine.isFixedCell(row, col) ? fixedTextPaint : textPaint;

        // 计算居中坐标
        int cellSize = getWidth() / 9;
        Rect bounds = new Rect();
        String text = String.valueOf(number);

        paint.getTextBounds(text, 0, text.length(), bounds);
        float x = col * cellSize + cellSize / 2f;
        float y = row * cellSize + cellSize / 2f + bounds.height() / 2f;

        canvas.drawText(text, x, y, paint);
    }

    /**
     * 绘制笔记内容
     */
    private void drawNoteContent(Canvas canvas, int row, int col) {
        boolean[] notes = gameEngine.getNotes(row, col);
        if (notes == null) return;

        int cellSize = getWidth() / 9;
        float noteSize = cellSize / 3f;  // 将单元格分为3x3小格

        for (int note = 1; note <= 9; note++) {
            if (notes[note - 1]) {
                // 计算小数字位置
                int noteRow = (note - 1) / 3;  // 0-2行
                int noteCol = (note - 1) % 3;  // 0-2列

                // 计算绘制坐标
                float x = col * cellSize + noteCol * noteSize + noteSize / 2;
                float y = row * cellSize + noteRow * noteSize + noteSize / 2
                        + noteTextPaint.getTextSize() / 3; // 垂直微调

                canvas.drawText(String.valueOf(note), x, y, noteTextPaint);
            }
        }
    }

    /**
     * 处理触摸事件（选择单元格）
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN && gameEngine != null) {
            int cellSize = getWidth() / 9;

            // 计算点击位置对应的行列
            selectedRow = (int) (event.getY() / cellSize);
            selectedCol = (int) (event.getX() / cellSize);

            // 有效范围检查
            if (isValidPosition(selectedRow, selectedCol)) {
                gameEngine.setSelectedCell(selectedRow, selectedCol);
                invalidate(); // 触发重绘
                return true;  // 消费事件
            }
        }
        return super.onTouchEvent(event);
    }

    private boolean isValidPosition(int row, int col) {
        return row >= 0 && row < 9 && col >= 0 && col < 9;
    }

    /**
     * 更新选中单元格位置（外部调用）
     */
    public void updateSelectedCell(int row, int col) {
        selectedRow = row;
        selectedCol = col;
        invalidate();
    }
}